package com.example.basecommon.utils;

import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

/**
 * @author dlj
 * des：获取Application 引用
 */

public class App {
    public static final Application INSTANCE;
    public static String APP_VERSION ;
    public static int APP_VERSION_CODE;

    static {
        Application app = null;
        try {
            app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication").invoke(null);
            if (app == null)
                throw new IllegalStateException("Static initialization of Applications must be on main thread.");
        } catch (final Exception e) {
            Log.e("APP","Failed to get current application from AppGlobals." + e.getMessage());
            try {
                app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication").invoke(null);
            } catch (final Exception ex) {
                Log.e("APP","Failed to get current application from ActivityThread." + e.getMessage());
            }
        } finally {
            INSTANCE = app;
        }
    }

    /**
     * 初始版本信息
     * 在Applicatoin初始话
     */
    public static void initVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            APP_VERSION = info.versionName;
            APP_VERSION_CODE = info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}